from rest_framework import serializers
from rest_framework.decorators import action
from django.db import models
from dvadmin.system.models import Carts, Users, Goods
from dvadmin.utils.json_response import DetailResponse, SuccessResponse, ErrorResponse
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet


class CartsSerializer(CustomModelSerializer):
    """
    Shopping cart management interface-serializer
    """
    # 添加店铺信息字段
    shop_info = serializers.SerializerMethodField()
    goods_info = serializers.SerializerMethodField()

    def get_shop_info(self, obj):
        """获取店铺信息"""
        try:
            if not obj.shop_id:
                return None
            shop_user = Users.objects.filter(id=obj.shop_id).first()
            if not shop_user:
                return None
            return {
                'shop_id': shop_user.id,
                'shop_name': shop_user.name,
                'shop_logo': shop_user.shop_logo,
                'shop_introduce': shop_user.shop_introduce,
                'shop_address': shop_user.shop_address
            }
        except Users.DoesNotExist:
            return None

    def get_goods_info(self, obj):
        """获取商品信息"""
        try:
            if not obj.goods_id:
                return None
            goods = Goods.objects.filter(id=obj.goods_id).first()
            if not goods:
                return None
            return {
                'goods_id': goods.id,
                'goods_name': goods.goods_name,
                'goods_price': goods.goods_price,
                'goods_image': goods.goods_image,
                'goods_description': goods.goods_description
            }
        except Goods.DoesNotExist:
            return None

    class Meta:
        model = Carts
        fields = "__all__"
        read_only_fields = ["id"]


class CartsCreateUpdateSerializer(CustomModelSerializer):
    """
    购物车管理接口 创建/更新时的序列化器
    """
    def validate(self, attrs):
        # 验证店铺ID
        shop_id = attrs.get('shop_id')
        if not isinstance(shop_id, int) or not Users.objects.filter(id=shop_id).exists():
            raise serializers.ValidationError({"shop_id": "Invalid shop ID"})
            
        # 验证商品ID
        goods_id = attrs.get('goods_id')
        if not isinstance(goods_id, int) or not Goods.objects.filter(id=goods_id).exists():
            raise serializers.ValidationError({"goods_id": "Invalid goods ID"})
            
        return super().validate(attrs)

    class Meta:
        model = Carts
        fields = '__all__'


class CartsViewSet(CustomModelViewSet):
    """
    Shopping cart management interface
    """
    queryset = Carts.objects.all()
    serializer_class = CartsSerializer
    create_serializer_class = CartsCreateUpdateSerializer

    def create(self, request, *args, **kwargs):
        """创建购物车项"""
        try:
            # 验证必填字段
            required_fields = ['shop_id', 'goods_id', 'goods_price', 'num']
            for field in required_fields:
                if field not in request.data:
                    return ErrorResponse(msg=f"Missing required field: {field}")

            # 验证店铺ID
            shop_id = request.data.get('shop_id')
            try:
                shop_id = int(shop_id)
                if not Users.objects.filter(id=shop_id).exists():
                    return ErrorResponse(msg="Shop not found")
            except (TypeError, ValueError):
                return ErrorResponse(msg="Invalid shop ID format")

            # 验证商品ID
            goods_id = request.data.get('goods_id')
            try:
                goods_id = int(goods_id)
                if not Goods.objects.filter(id=goods_id).exists():
                    return ErrorResponse(msg="Goods not found")
            except (TypeError, ValueError):
                return ErrorResponse(msg="Invalid goods ID format")

            # 设置用户ID
            request.data['user_id'] = request.user.id
            
            # 创建购物车项
            serializer = self.get_serializer(data=request.data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            
            return DetailResponse(data=serializer.data, msg="Successfully added to cart")
        except Exception as e:
            return ErrorResponse(msg=f"Failed to add to cart: {str(e)}")

    def list(self, request, *args, **kwargs):
        """Get shopping cart list"""
        try:
            # 获取当前用户的购物车列表
            queryset = self.get_queryset().filter(user_id=request.user.id)
            
            # 按店铺分组
            shop_carts = {}
            for cart in queryset:
                shop_id = cart.shop_id
                if shop_id not in shop_carts:
                    # 获取店铺信息
                    shop_user = Users.objects.get(id=shop_id)
                    shop_carts[shop_id] = {
                        'shop_info': {
                            'shop_id': shop_user.id,
                            'shop_name': shop_user.name,
                            'shop_logo': shop_user.shop_logo,
                            'shop_introduce': shop_user.shop_introduce,
                            'shop_address': shop_user.shop_address
                        },
                        'goods_list': []
                    }
                
                # 获取商品信息
                goods = Goods.objects.get(id=cart.goods_id)
                shop_carts[shop_id]['goods_list'].append({
                    'cart_id': cart.id,
                    'goods_id': goods.id,
                    'goods_name': goods.goods_name,
                    'goods_price': cart.goods_price,
                    'goods_num': cart.num,
                    'goods_image': cart.goods_img,
                    'goods_description': goods.goods_description
                })

            # 转换为列表格式
            result = [
                {
                    'shop_info': data['shop_info'],
                    'goods_list': data['goods_list']
                }
                for data in shop_carts.values()
            ]

            return SuccessResponse(data=result, msg="Successfully retrieved cart list")
            
        except Exception as e:
            return ErrorResponse(msg=f"Failed to get cart list: {str(e)}")

    @action(methods=['GET'], detail=True)
    def role_get_menu(self, request):
        app_user_queryset = Carts.objects.filter(users__id=request.user.id).values_list('data_range', flat=True)
        return DetailResponse(data=app_user_queryset)

    def remove_duplicates(lst):
        return list(set(lst))

    @action(methods=['GET'], detail=False)
    def get_user_carts(self, request):
        try:
            # 获取当前用户的购物车列表
            carts = Carts.objects.filter(user_id=request.user.id)
            
            # 获取所有不重复的店铺ID
            shop_ids = carts.values_list('shop_id', flat=True).distinct()
            
            listData = []
            for shop_id in shop_ids:
                if shop_id is not None:  # 添加空值检查
                    shop_carts = carts.filter(shop_id=shop_id)
                    shop = Users.objects.filter(id=shop_id).first()
                    if shop:  # 确保店铺存在
                        json_data = {
                            "shop": {
                                "id": shop.id,
                                "name": shop.name,
                                "shop_logo": shop.shop_logo,
                                "shop_introduce": shop.shop_introduce,
                                "shop_address": shop.shop_address
                            },
                            "carts": list(shop_carts.values())
                        }
                        listData.append(json_data)
            
            return SuccessResponse(data=listData)
        except Exception as e:
            return ErrorResponse(msg=f"Failed to get cart list: {str(e)}")

    @action(methods=['DELETE'], detail=False)
    def delete_carts(self, request):
        app_user_queryset = Carts.objects.filter(id=request.data.get("id")).delete()
        return DetailResponse(data=app_user_queryset)
